package bma.common.langutil.jmshell.command;

import java.io.File;

import bma.common.langutil.core.ExceptionUtil;
import bma.common.langutil.core.StringUtil;
import bma.common.langutil.core.ValueUtil;
import bma.common.langutil.io.IOUtil;
import bma.common.langutil.jmshell.Session;
import bma.common.langutil.jmshell.cmdopt.CommandOptionParser;

public class ExecCommand extends AbstractSimpleCommandProcessor {

	public ExecCommand() {
		super("exec");
		setArgsTips("[commands]");
	}

	@Override
	public CommandOptionParser createCommandOption(Session session) {
		CommandOptionParser r = new CommandOptionParser();
		r.addStringOption('f', "file", "exec commands from file");
		return r;
	}

	@Override
	public boolean processCommand(Session session, String cmd,
			CommandOptionParser options) {
		String f = options.getOptionValue("file", "");
		if (ValueUtil.notEmpty(f)) {
			execFile(session, f);
			return true;
		}
		String[] args = options.getRemainingArgs();
		if (args != null && args.length > 0) {
			for (int i = 0; i < args.length; i++) {
				String commands = args[i];
				String[] cmds = StringUtil.tokenSplit(commands, ";");
				exec(session, cmds);
			}
			return true;
		}
		session.writeln(getHelp(session));
		return true;
	}

	public void execFile(Session s, String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			s.writeln("[ERROR] '" + fileName + "' not exists");
			return;
		}
		if (file.isDirectory()) {
			s.writeln("[ERROR] '" + fileName + "' is directory");
			return;
		}
		try {
			String commands = IOUtil.readFileToString(file, "UTF-8");
			String[] cmdlist = StringUtil.tokenSplit(commands, "\n;");
			exec(s, cmdlist);
		} catch (Exception e) {
			throw ExceptionUtil.throwRuntime(e);
		}
	}

	public void exec(Session s, String[] cmdlist) {
		for (int i = 0; i < cmdlist.length; i++) {
			String command = cmdlist[i].trim();
			s.writeln(">> " + command);
			s.execute(command);
		}
	}

}